<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css"/>




  <link href="//fonts.googleapis.com/css?family=Lato:300,400,700,400italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">



<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=0.5.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="NodeJS,微信," />








  <link rel="shortcut icon" type="image/x-icon" href="/images/favicon.ico?v=0.5.0" />






<meta name="description" content="前段时间帮忙做一个微信后台开发，并且用了Node + Mongo，做一次实践，后面又添加了一些功能，整个项目开始变得系统，做了一段时间，对于整个系统的把握变得清晰，Node的使用也有了些思路，过程中遇到很多问题，虽然最后项目作废了，但是笔记还是要做的，这里就记录下开发中遇到的问题。">
<meta property="og:type" content="article">
<meta property="og:title" content="微信公号Node开发「零」之项目建立">
<meta property="og:url" content="http://lijundong.com/2016/06/19/微信公号Node开发「零」/index.html">
<meta property="og:site_name" content="Leeon's BLOG">
<meta property="og:description" content="前段时间帮忙做一个微信后台开发，并且用了Node + Mongo，做一次实践，后面又添加了一些功能，整个项目开始变得系统，做了一段时间，对于整个系统的把握变得清晰，Node的使用也有了些思路，过程中遇到很多问题，虽然最后项目作废了，但是笔记还是要做的，这里就记录下开发中遇到的问题。">
<meta property="og:image" content="http://7xlkdt.com1.z0.glb.clouddn.com/16-7-22/12502005-Bt5ywJrIEAAKJQt.jpg-large">
<meta property="og:updated_time" content="2016-07-22T12:01:34.243Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="微信公号Node开发「零」之项目建立">
<meta name="twitter:description" content="前段时间帮忙做一个微信后台开发，并且用了Node + Mongo，做一次实践，后面又添加了一些功能，整个项目开始变得系统，做了一段时间，对于整个系统的把握变得清晰，Node的使用也有了些思路，过程中遇到很多问题，虽然最后项目作废了，但是笔记还是要做的，这里就记录下开发中遇到的问题。">
<meta name="twitter:image" content="http://7xlkdt.com1.z0.glb.clouddn.com/16-7-22/12502005-Bt5ywJrIEAAKJQt.jpg-large">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"left","display":"hide"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: 'Author'
    }
  };
</script>

  <title> 微信公号Node开发「零」之项目建立 | Leeon's BLOG </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?c6907c4f3552baba34e8ee2c5980996d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>








  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">Leeon's BLOG</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-home fa-fw"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-th fa-fw"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-user fa-fw"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-archive fa-fw"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-tags fa-fw"></i> <br />
            
            Tags
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                微信公号Node开发「零」之项目建立
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2016-06-19T11:04:34+08:00" content="2016-06-19">
              2016-06-19
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/NodeJS/" itemprop="url" rel="index">
                    <span itemprop="name">NodeJS</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2016/06/19/微信公号Node开发「零」/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/06/19/微信公号Node开发「零」/" itemprop="commentsCount"></span>
                </a>
              </span>
            

          

          

          
          
             <span id="/2016/06/19/微信公号Node开发「零」/" class="leancloud_visitors" data-flag-title="微信公号Node开发「零」之项目建立">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>前段时间帮忙做一个微信后台开发，并且用了Node + Mongo，做一次实践，后面又添加了一些功能，整个项目开始变得系统，做了一段时间，对于整个系统的把握变得清晰，Node的使用也有了些思路，过程中遇到很多问题，虽然最后项目作废了，但是笔记还是要做的，这里就记录下开发中遇到的问题。<br><a id="more"></a></p>
<h3 id="NodeJS"><a href="#NodeJS" class="headerlink" title="NodeJS"></a>NodeJS</h3><p>首先需要理清楚，Node不是一门新的语言，使用的语法是JavaScript的核心语法，而Node只是JS代码运行环境。<br>参考下图(作者<a href="https://twitter.com/BusyRich/status/494959181871316992" target="_blank" rel="external">@BusyRich</a>)可以更清晰的理解Node的运行过程。</p>
<p><img src="http://7xlkdt.com1.z0.glb.clouddn.com/16-7-22/12502005-Bt5ywJrIEAAKJQt.jpg-large" alt="Node运行"></p>
<p>运行过程如下:</p>
<blockquote>
<ul>
<li>V8引擎解析JavaScript脚本</li>
<li>解析后的代码调用Node API</li>
<li>libuv负责Node API的执行。它将不同的任务分配给不同的线程，形成一个Event Loop，以异步方式将任务的执行结果返回给V8引擎。</li>
<li>v8引擎再将结果返回给用户。</li>
</ul>
</blockquote>
<p>之前在<a href="http://www.lijundong.com/2016/07/15/%E5%86%8D%E8%B0%88setTimeout%E4%B8%8EsetInterval/" target="_blank" rel="external">再谈setTimeout与setInterval</a>中讨论过JavaScript中的Event Loop，Node中的Event Loop机制有机会可以看下。</p>
<p>所以对于前端开发者来说，上手NodeJS会比较容易些，运行方式也简单</p>
<ul>
<li>一是在终端下打开Node运行环境<code>node</code>命令，输入<code>console.log(&quot;hello node&quot;);</code>回车即可看到<code>hello node</code>，</li>
<li>二是新建example.js，内容为<code>console.log(&quot;hello node&quot;);</code>，在终端下<code>node example.js</code>命令执行JS文件，<code>hello node</code>再次出现。<br>熟悉python的同学是不是觉得与python的运行方式撞脸了。</li>
</ul>
<p>言归正传，回到项目上，这里用Express + MongoDB组合。</p>
<h3 id="Express"><a href="#Express" class="headerlink" title="Express"></a>Express</h3><p>Express默认使用Jade作为前端模板，但在建立项目时，提供选择ejs的参数，我习惯使用ejs，所以现在创建项目，wechatGame。<br><code>express -e wechatGame</code><br>项目创建完成后，该目录下出现<code>/wechatGame</code>目录，结构如下<br><figure class="highlight gherkin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">|<span class="string">-- app.js          //主文件</span><br><span class="line"></span>|<span class="string">-- bin             //启动文件</span><br><span class="line"></span>|<span class="string">   `-- www</span><br><span class="line"></span>|<span class="string">-- package.json    //配置文件</span><br><span class="line"></span>|<span class="string">-- public          //公共文件</span><br><span class="line"></span>|<span class="string">   </span>|<span class="string">-- images</span><br><span class="line"></span>|<span class="string">   </span>|<span class="string">-- javascripts</span><br><span class="line"></span>|<span class="string">   `-- stylesheets</span><br><span class="line"></span>|<span class="string">       `-- style.css</span><br><span class="line"></span>|<span class="string">-- routes          //路由</span><br><span class="line"></span>|<span class="string">   </span>|<span class="string">-- index.js</span><br><span class="line"></span>|<span class="string">   `-- users.js</span><br><span class="line">`-- views           //页面</span><br><span class="line">    </span>|<span class="string">-- error.ejs</span><br><span class="line">    `-- index.ejs</span></span><br></pre></td></tr></table></figure></p>
<p>项目建好，接着安装所需的依赖，编辑package.json，除了已有的包，还需要添加操作MongoDB的包，我选用了mongoose，所以最终的packa.json内容如下<br><figure class="highlight xquery"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">  <span class="string">"name"</span>: <span class="string">"wechatGame"</span>,</span><br><span class="line">  <span class="string">"version"</span>: <span class="string">"0.0.0"</span>,</span><br><span class="line">  <span class="string">"private"</span>: <span class="literal">true</span>,</span><br><span class="line">  <span class="string">"scripts"</span>: &#123;</span><br><span class="line">    <span class="string">"start"</span>: <span class="string">"node ./bin/www"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="string">"dependencies"</span>: &#123;</span><br><span class="line">    <span class="string">"body-parser"</span>: <span class="string">"~1.15.1"</span>,</span><br><span class="line">    <span class="string">"cookie-parser"</span>: <span class="string">"~1.4.3"</span>,</span><br><span class="line">    <span class="string">"debug"</span>: <span class="string">"~2.2.0"</span>,</span><br><span class="line">    <span class="string">"ejs"</span>: <span class="string">"~2.4.1"</span>,</span><br><span class="line">    <span class="string">"express"</span>: <span class="string">"~4.13.4"</span>,</span><br><span class="line">    <span class="string">"morgan"</span>: <span class="string">"~1.7.0"</span>,</span><br><span class="line">    <span class="string">"serve-favicon"</span>: <span class="string">"~2.3.0"</span>,</span><br><span class="line">    <span class="string">"mongoose"</span>: <span class="string">"~4.4.15"</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在项目目录下安装<br><code>npm install</code><br>安装完成，启动项目，express4.0之后，启动方式由<code>node app.js</code>变成<code>npm start</code>。<br>我用的是4.13.4，所以<code>npm start</code>启动服务器</p>
<p>打开浏览器，访问<code>localhost:3000</code></p>
<p>hello express</p>
<hr>
<p>觉得不能把理解的东西讲得透彻，面面俱到，迟迟不敢下手，写了删，删了写，关于写作还有很多东西需要学习，行文思路清晰，文字表达精炼，这些都是需要不断的写来锻炼的。<br>Anyway,done is better than perfect!</p>
<p>参考：</p>
<ul>
<li><p><a href="http://www.ruanyifeng.com/blog/2014/10/event-loop.html" target="_blank" rel="external">JavaScript 运行机制详解：再谈Event Loop</a></p>
</li>
<li></li>
</ul>

      
    </div>

    <div>
      
        
      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/NodeJS/" rel="tag">#NodeJS</a>
          
            <a href="/tags/微信/" rel="tag">#微信</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/06/18/node-js中-dirname与-的区别/" rel="next" title="node.js中__dirname与./的区别">
                <i class="fa fa-chevron-left"></i> node.js中__dirname与./的区别
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/06/27/自寻烦恼/" rel="prev" title="自寻烦恼">
                自寻烦恼 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/06/19/微信公号Node开发「零」/"
           data-title="微信公号Node开发「零」之项目建立" data-url="http://lijundong.com/2016/06/19/微信公号Node开发「零」/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            Overview
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://7xlkdt.com1.z0.glb.clouddn.com/16-3-18/59657432.jpg"
               alt="Leeon" />
          <p class="site-author-name" itemprop="name">Leeon</p>
          <p class="site-description motion-element" itemprop="description">笔记来的</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">32</span>
              <span class="site-state-item-name">posts</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">6</span>
                <span class="site-state-item-name">categories</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">54</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/lijundong" target="_blank">
                  
                    <i class="fa fa-github-square"></i> GitHub
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://plus.google.com/u/0/105476317091375278758" target="_blank">
                  
                    <i class="fa fa-google-plus-square"></i> Google+
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/Jundong_Li" target="_blank">
                  
                    <i class="fa fa-twitter"></i> Twitter
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.facebook.com/coderleon?ref=bookmarks" target="_blank">
                  
                    <i class="fa fa-facebook-square"></i> facebook
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.douban.com/people/103163980/" target="_blank">
                  
                    <i class="fa fa-spinner"></i> 豆
                  
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/leon-lee-42" target="_blank">
                  
                    <i class="fa fa-spinner"></i> 知
                  
                </a>
              </span>
            
          
        </div>

        
        

        
        <div class="links-of-blogroll motion-element">
          
        </div>

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc-indicator-top post-toc-indicator">
            <i class="fa fa-angle-double-up"></i>
          </div>
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#NodeJS"><span class="nav-text">NodeJS</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Express"><span class="nav-text">Express</span></a></li></ol></div>
            
          </div>
          <div class="post-toc-indicator-bottom post-toc-indicator">
            <i class="fa fa-angle-double-down"></i>
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Leeon</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io" rel="external nofollow">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">
    NexT.Mist
  </a>
</div>



      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  


  




<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>

  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>

  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=0.5.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=0.5.0"></script>



  
  

  
  
<script type="text/javascript" src="/js/src/scrollspy.js?v=0.5.0"></script>

<script type="text/javascript" id="sidebar.toc.highlight">
  $(document).ready(function () {
    var tocSelector = '.post-toc';
    var $tocSelector = $(tocSelector);
    var activeCurrentSelector = '.active-current';

    $tocSelector
      .on('activate.bs.scrollspy', function () {
        var $currentActiveElement = $(tocSelector + ' .active').last();

        removeCurrentActiveClass();
        $currentActiveElement.addClass('active-current');

        $tocSelector[0].scrollTop = $currentActiveElement.position().top;
      })
      .on('clear.bs.scrollspy', function () {
        removeCurrentActiveClass();
      });

    function removeCurrentActiveClass () {
      $(tocSelector + ' ' + activeCurrentSelector)
        .removeClass(activeCurrentSelector.substring(1));
    }

    function processTOC () {
      getTOCMaxHeight();
      toggleTOCOverflowIndicators();
    }

    function getTOCMaxHeight () {
      var height = $('.sidebar').height() -
                   $tocSelector.position().top -
                   $('.post-toc-indicator-bottom').height();

      $tocSelector.css('height', height);

      return height;
    }

    function toggleTOCOverflowIndicators () {
      tocOverflowIndicator(
        '.post-toc-indicator-top',
        $tocSelector.scrollTop() > 0 ? 'show' : 'hide'
      );

      tocOverflowIndicator(
        '.post-toc-indicator-bottom',
        $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
      )
    }

    $(document).on('sidebar.motion.complete', function () {
      processTOC();
    });

    $('body').scrollspy({ target: tocSelector });
    $(window).on('resize', function () {
      if ( $('.sidebar').hasClass('sidebar-active') ) {
        processTOC();
      }
    });

    onScroll($tocSelector);

    function onScroll (element) {
      element.on('mousewheel DOMMouseScroll', function (event) {
          var oe = event.originalEvent;
          var delta = oe.wheelDelta || -oe.detail;

          this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
          event.preventDefault();

          toggleTOCOverflowIndicators();
      });
    }

    function tocOverflowIndicator (indicator, action) {
      var $indicator = $(indicator);
      var opacity = action === 'show' ? 1 : 0;
      $indicator.velocity ?
        $indicator.velocity('stop').velocity({
          opacity: opacity
        }, { duration: 100 }) :
        $indicator.stop().animate({
          opacity: opacity
        }, 100);
    }

  });
</script>

<script type="text/javascript" id="sidebar.nav">
  $(document).ready(function () {
    var html = $('html');
    var TAB_ANIMATE_DURATION = 200;
    var hasVelocity = $.isFunction(html.velocity);

    $('.sidebar-nav li').on('click', function () {
      var item = $(this);
      var activeTabClassName = 'sidebar-nav-active';
      var activePanelClassName = 'sidebar-panel-active';
      if (item.hasClass(activeTabClassName)) {
        return;
      }

      var currentTarget = $('.' + activePanelClassName);
      var target = $('.' + item.data('target'));

      hasVelocity ?
        currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
          target
            .velocity('stop')
            .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
            .addClass(activePanelClassName);
        }) :
        currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
          currentTarget.hide();
          target
            .stop()
            .css({'opacity': 0, 'display': 'block'})
            .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
              currentTarget.removeClass(activePanelClassName);
              target.addClass(activePanelClassName);
            });
        });

      item.siblings().removeClass(activeTabClassName);
      item.addClass(activeTabClassName);
    });

    $('.post-toc a').on('click', function (e) {
      e.preventDefault();
      var targetSelector = NexT.utils.escapeSelector(this.getAttribute('href'));
      var offset = $(targetSelector).offset().top;
      hasVelocity ?
        html.velocity('stop').velocity('scroll', {
          offset: offset  + 'px',
          mobileHA: false
        }) :
        $('html, body').stop().animate({
          scrollTop: offset
        }, 500);
    });

    // Expand sidebar on post detail page by default, when post has a toc.
    NexT.motion.middleWares.sidebar = function () {
      var $tocContent = $('.post-toc-content');

      if (CONFIG.sidebar.display === 'post' || CONFIG.sidebar.display === 'always') {
        if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
          NexT.utils.displaySidebar();
        }
      }
    };
  });
</script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=0.5.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"coderleon"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
  





  
  
  
  <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
  </script>

  <script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for (i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  </script>

  
    <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("pJdYd3bVkuCMKiGlqFilwfbY-gzGzoHsz", "5HFxgKVCT5jJDtW3gHibs0Tn");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



 
</body>
</html>
